package com.turing.post.common.impl;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.Region;
import com.turing.post.common.util.RegionDao;
import com.turing.post.util.PCPSUtil;

/**
 * @author zxp
 * @Jan 16, 2013
 */
@Stateless(mappedName = "common.impl.RegionDaoImpl")
@Remote
@Local
public class RegionDaoImpl implements RegionDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@SuppressWarnings("unchecked")
	@Override
	public List<Region> getRegionList(String superRegionNo) {
		String sql = "";
		if (PCPSUtil.isEmpty(superRegionNo)) {
			sql = "select * from Region t where regionlevel=0 order by regionno";
		} else {
			sql = "select * from Region t where superregionno='"
					+ superRegionNo + "' order by regionno";
		}
		Query query = _em.createNativeQuery(sql, Region.class);
		return query.getResultList();
	}

	@Override
	public Region getRegionByRegionNo(String regionNo) {
		return _em.find(Region.class, regionNo);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Region> getRegionTreeList(String regionNo) {
		String sql = "select * from Region where regionno like ?1 order by regionNo";
		Query query = _em.createNativeQuery(sql, Region.class);
		if (PCPSUtil.isEmpty(regionNo))
			query.setParameter(1, "%%");
		else
			query.setParameter(1, regionNo + "%");
		return query.getResultList();
	}
}